'use client'

import { useState, useEffect, MouseEvent, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { ArrowLeftIcon } from '@heroicons/react/24/outline'
import Button from '@/components/ui/Button'
import ButtonLink from '@/components/ui/ButtonLink'

interface Experiment {
  id: string
  title: string
  stagesCount?: number
}

function NewQuestionContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { data: session, status } = useSession()
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    experimentId: searchParams.get('experimentId') || '',
  })
  const [experiments, setExperiments] = useState<Experiment[]>([])
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  // 监听实验列表状态变化的调试代码
  useEffect(() => {
    console.log('实验列表状态已更新:', experiments)
  }, [experiments])

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login')
      return
    }

    if (status === 'loading') return

    // 会话已加载完成，直接获取实验列表
    // 保持loading=true状态，由fetchExperiments负责设置loading=false
    fetchExperiments()
  }, [status])

  const fetchExperiments = async () => {
    try {
      setLoading(true)
      console.log('开始获取实验列表...')
      const response = await fetch('/api/experiments')
      
      if (!response.ok) {
        throw new Error('获取实验列表失败')
      }
      
      const data = await response.json()
      console.log('成功获取实验列表:', data)
      
      // 确保data是数组形式
      if (Array.isArray(data)) {
        // 强制转换数据格式，确保包含id和title字段
        const formattedData = data.map(item => ({
          id: item.id,
          title: item.title || '未命名实验',
          stagesCount: item.stagesCount
        }))
        
        console.log('格式化后的实验列表:', formattedData)
        setExperiments(formattedData)
        
        if (formattedData.length === 0) {
          setError('没有可用的实验列表')
        } else {
          // 显示获取到的第一项实验信息，方便调试
          console.log(`获取到${formattedData.length}个实验，第一个实验:`, 
                     formattedData[0] ? `ID: ${formattedData[0].id}, 标题: ${formattedData[0].title}` : '无')
        }
      } else {
        console.error('API返回的数据不是数组:', data)
        setExperiments([])
        setError('获取实验列表返回了无效格式')
      }
    } catch (err: any) {
      console.error('获取实验列表失败:', err)
      setError(err.message || '获取实验列表失败')
      setExperiments([])
    } finally {
      setLoading(false)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }))
  }

  // 添加点击事件阻止默认行为的处理函数
  const handleSelectClick = (e: MouseEvent<HTMLSelectElement>) => {
    // 只处理选择框的点击，不阻止其他点击
    e.stopPropagation() // 阻止事件冒泡
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.title.trim() || !formData.content.trim() || !formData.experimentId) {
      setError('请填写完整的表单信息')
      return
    }
    
    try {
      setSubmitting(true)
      setError('')
      
      const response = await fetch('/api/forum/questions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '创建问题失败')
      }
      
      const data = await response.json()
      
      // 创建成功后跳转到问题详情页
      router.push(`/forum/${data.question.id}`)
    } catch (err: any) {
      setError(err.message || '创建问题失败')
      setSubmitting(false)
    }
  }

  if (status === 'loading' || loading) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <div className="flex justify-center">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
            </div>
            <p className="mt-4 text-gray-600">加载实验列表中，请稍候...</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="py-8">
      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="mb-6">
          <Link
            href="/forum"
            className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700"
          >
            <ArrowLeftIcon className="h-4 w-4 mr-1" />
            返回论坛
          </Link>
        </div>

        <div className="bg-white shadow sm:rounded-lg overflow-hidden">
          <div className="px-4 py-5 sm:px-6 border-b border-gray-200">
            <h1 className="text-lg font-medium text-gray-900">
              提出新问题
            </h1>
            <p className="mt-1 text-sm text-gray-500">
              清晰详细的问题更容易得到解答
            </p>
          </div>

          <div className="px-4 py-5 sm:p-6">
            {error && (
              <div className="mb-6 rounded-md bg-red-50 p-4">
                <div className="text-sm text-red-700">{error}</div>
              </div>
            )}

            {/* DEBUG信息 - 调试完成后可以移除 */}
            {/* {experiments.length > 0 && (
              <div className="mb-4 p-2 bg-gray-50 rounded text-xs">
                <p>已获取{experiments.length}个实验，可在下拉列表中选择</p>
                <details>
                  <summary>实验列表数据 (点击展开)</summary>
                  <pre className="mt-1 text-xs overflow-auto max-h-40">
                    {JSON.stringify(experiments, null, 2)}
                  </pre>
                </details>
              </div>
            )} */}

            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <label htmlFor="experimentId" className="block text-sm font-medium text-gray-700">
                  选择实验
                </label>
                <select
                  id="experimentId"
                  name="experimentId"
                  value={formData.experimentId}
                  onChange={handleChange}
                  onClick={handleSelectClick}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  required
                >
                  <option value="">-- 请选择实验 --</option>
                  {experiments && experiments.length > 0 && 
                    experiments.map((experiment) => (
                      <option key={experiment.id} value={experiment.id}>
                        {experiment.title || '未命名实验'} {experiment.stagesCount ? `(${experiment.stagesCount}个阶段)` : ''}
                      </option>
                    ))
                  }
                </select>
                {experiments.length === 0 && !loading && (
                  <p className="mt-1 text-xs text-red-500">没有找到可用的实验，请先创建实验</p>
                )}
                {/* 添加刷新按钮 */}
                <button 
                  type="button" 
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    fetchExperiments();
                  }}
                  className="mt-1 text-xs text-blue-600 hover:text-blue-800"
                >
                  刷新实验列表
                </button>
              </div>

              <div>
                <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                  问题标题
                </label>
                <input
                  type="text"
                  id="title"
                  name="title"
                  value={formData.title}
                  onChange={handleChange}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  placeholder="简明扼要地描述你的问题"
                  required
                />
              </div>

              <div>
                <label htmlFor="content" className="block text-sm font-medium text-gray-700">
                  问题详情
                </label>
                <textarea
                  id="content"
                  name="content"
                  rows={8}
                  value={formData.content}
                  onChange={handleChange}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  placeholder="详细描述你的问题，包括你已经尝试过的解决方法"
                  required
                />
              </div>

              <div className="flex justify-end">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => router.back()}
                  className="mr-3"
                >
                  取消
                </Button>
                <Button
                  type="submit"
                  disabled={submitting}
                >
                  {submitting ? '提交中...' : '发布问题'}
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}

export default function NewQuestionPage() {
  return (
    <Suspense fallback={
      <div className="py-8">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <div className="flex justify-center">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
            </div>
            <p className="mt-4 text-gray-600">加载中...</p>
          </div>
        </div>
      </div>
    }>
      <NewQuestionContent />
    </Suspense>
  )
} 